package com.sky.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getturnoverStatistics(LocalDate begin, LocalDate end) {
        //存放从begin到end的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end.plusDays(1))){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        List<Double> turnoverList = new ArrayList<>();
        //查询每天完成订单的营业额
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            if (turnover == null){
                turnover = 0.0;
            }
            turnoverList.add(turnover);
        }
        //封装返回结果
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 用户统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getuserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end.plusDays(1))){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        //新增用户列表
        List<Integer> newUserList = new ArrayList<>();
        //全部用户列表
        List<Integer> totalUserList = new ArrayList<>();

        //查询所有用户列表
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("end",endTime);
            Integer totalUser = userMapper.getUserCount(map);
            map.put("begin",beginTime);
            //每天新增用户数
            Integer newUser = userMapper.getUserCount(map);
            //每天总用户数
            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }
       UserReportVO userReportVO =  UserReportVO.builder()
                                .dateList(StringUtils.join(dateList,","))
                                .newUserList(StringUtils.join(newUserList,","))
                                .totalUserList(StringUtils.join(totalUserList,","))
                                .build();

        //查询新增用户列表
        return userReportVO;
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    //每日订单数 每日有效订单数 订单总数 有效订单数 订单完成率
    public OrderReportVO getorderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end.plusDays(1))){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        //每日订单数列表
        List<Integer> dailyOrderslist = new ArrayList<>();
        //订单总数
        Integer orderCount = 0;
        //每日有效订单数
        List<Integer> dailyEffectiveOrderslist = new ArrayList<>();
        //有效订单总数
        Integer EffectiveOrderCount = 0;
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("end",endTime);
            map.put("begin",beginTime);
            //查询每天订单数
           Integer dailyOrderCount = orderMapper.getOrderCount(map);
           map.put("status",Orders.COMPLETED);
           //查询每天有效订单数
           Integer dailyEffectiveOrderCount = orderMapper.getOrderCount(map);
           //每天订单数
            dailyOrderslist.add(dailyOrderCount);
            //每天有效订单数
            dailyEffectiveOrderslist.add(dailyEffectiveOrderCount);
           //计算订单总数
           orderCount += dailyOrderCount;
           //计算有效订单总数
           EffectiveOrderCount += dailyEffectiveOrderCount;
        }
        Double orderCompletionRate =  EffectiveOrderCount.doubleValue() / orderCount;

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(dailyOrderslist,","))
                .totalOrderCount(orderCount)
                .validOrderCountList(StringUtils.join(dailyEffectiveOrderslist,","))
                .validOrderCount(EffectiveOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    //商品名称列表 销量列表
    public SalesTop10ReportVO getSalesTop10Report(LocalDate begin, LocalDate end) {

        List<String> dishOrSetmealNameList = new ArrayList<>();
        List<Integer> sales = new ArrayList<>();

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //根据动态条件查询商品名称和销量封装到GoodsSalesDTO中
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime,endTime);
        //遍历取出商品名称和销量
        for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOList) {
            String name = goodsSalesDTO.getName();
            dishOrSetmealNameList.add(name);
            Integer number = goodsSalesDTO.getNumber();
            sales.add(number);
        }

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(dishOrSetmealNameList,","))
                .numberList(StringUtils.join(sales,","))
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessDate(HttpServletResponse response) {
        //1查询数据库，获得营业数据------>最近三十天数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getbusinessData(LocalDateTime.of(dateBegin,LocalTime.MIN),LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2通过poi将营业数据写入到excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //填充数据
            //获取文件的标签页sheet1
            XSSFSheet sheet = excel.getSheetAt(0);
            //获取第二行
            XSSFRow row = sheet.getRow(1);
            //填充数据————>时间
            row.getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);
            //获得第四行--->填写相关数据
            row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //获得第五行---->填写相关数据
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0 ; i < 30 ; i++){
                LocalDate date = dateBegin.plusDays(i);
                //查询某天的营业数据
                BusinessDataVO businessData = workspaceService.getbusinessData(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3通过输出流把excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);


            //4关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
